#!/usr/bin/env python3
# coding: utf-8
"""
2025-05-30 检查项目
"""

from PySide6.QtCore import Slot, QSize
from PySide6.QtGui import QAction, QKeySequence,QIntValidator, QTextCursor   
from PySide6.QtWidgets import QMainWindow, QApplication, QVBoxLayout, QHBoxLayout, QPushButton, QWidget,QLineEdit, QMessageBox, QTableWidget, QTableWidgetItem, QHeaderView, QAbstractItemView, QLabel,QCheckBox,QTextEdit,QGroupBox,QComboBox,QDateTimeEdit,QGridLayout
from PySide6.QtCore import Qt, QModelIndex,QMetaObject,Q_ARG,QDateTime
from PySide6.QtGui import QGuiApplication, QCloseEvent
## from PySide6.QtCore.Qt import 
# from top.wardyan.core.widges.controlls import WTextEdit as QLineEdit

##from PySide6.QtCore import WindowState

## from top.wardyan.core.utils import winformutils
from top.wardyan.core.action.baseaction import WMainWindow,WQdialog
from top.wardyan.core.vo.vos import *
from top.wardyan.core.widges.tables import WTableView

##from warningmain import *
from top.wardyan.core.wdb.core.DBPool import POOL

from top.wardyan.core.vo.vos import *
from top.wardyan.core.wdb.core.db import *
from config import Config
from top.wardyan.core.sqlite import sqliteconfigs

import threading
import time
import re
import sys

from apscheduler.schedulers.background import BackgroundScheduler
from top.wardyan.core.utils.common import *
from top.wardyan.core.wdb.core.dic import *
import uuid

from top.wardyan.projects.checktool_manager.main.checktool_manager_const import *


SQL_FIND = "EXEC dbo.yp_check_view @pBeginDate = '1900-01-01', @pEndDate = '2078-12-31 23:59:59', @pText = %s, @pKind = 0, @pType = 0, @pExtID = %d"



        

class ChecktoolCheckEditShell (WQdialog) :
        
    def __init__(self, checkid) -> None:
        ##global cn
        super().__init__("ChecktoolCheckEditShell")
        self.editable = False
        self.checkid = checkid
        self.table : WTableView = None
        self.main()
        ## self.refreshTable()
        self.load()

    def button_click_add(self) :
        pass


    def handle_bind(self, isDeBind : bool = False):
        if isDeBind :
            try :
                self.xNameLineEdit.textChanged.disconnect(self.on_input_changed)
                self.xTableNameLineEdit.textChanged.disconnect(self.on_input_changed)
                self.xErrorCodeLineEdit.textChanged.disconnect(self.on_input_changed)
                self.xUrlLineEdit.textChanged.disconnect(self.on_input_changed)
                self.xMaxTimeQtyLineEdit.textChanged.disconnect(self.on_input_changed)

                self.xKindComboBox.currentIndexChanged.disconnect(self.on_input_changed)
                self.xTypeComboBox.currentIndexChanged.disconnect(self.on_input_changed)
                self.xLevelComboBox.currentIndexChanged.disconnect(self.on_input_changed)

                self.xSQLTextEdit.textChanged.disconnect(self.on_input_changed)
                self.xSQLTemplateTextEdit.textChanged.disconnect(self.on_input_changed)

                self.xMinVersionEdit.dateTimeChanged.disconnect(self.on_input_changed)
            except BaseException as e :
                pass
        else : 
            self.xNameLineEdit.textChanged.connect(self.on_input_changed)
            self.xTableNameLineEdit.textChanged.connect(self.on_input_changed)
            self.xErrorCodeLineEdit.textChanged.connect(self.on_input_changed)
            self.xUrlLineEdit.textChanged.connect(self.on_input_changed)
            self.xMaxTimeQtyLineEdit.textChanged.connect(self.on_input_changed)

            self.xKindComboBox.currentIndexChanged.connect(self.on_input_changed)
            self.xTypeComboBox.currentIndexChanged.connect(self.on_input_changed)
            self.xLevelComboBox.currentIndexChanged.connect(self.on_input_changed)

            self.xSQLTextEdit.textChanged.connect(self.on_input_changed)
            self.xSQLTemplateTextEdit.textChanged.connect(self.on_input_changed)

            self.xMinVersionEdit.dateTimeChanged.connect(self.on_input_changed)
    def on_input_changed(self):
        self.btnSave.setEnabled(True)
        self.btnEdit.setEnabled(False)
        self.btnAudit.setEnabled(False)
        self.btnAdd.setEnabled(False)
        self.btnDel.setEnabled(False)

    def on_input_inited(self) :
        if self.checkid is not None and self.checkid > 0 :
            self.btnSave.setEnabled(False)
            self.btnEdit.setEnabled(True)
            self.btnAudit.setEnabled(True)
            self.btnAdd.setEnabled(True)
            self.btnDel.setEnabled(False)
        else :
            self.btnSave.setEnabled(True)
            self.btnEdit.setEnabled(False)
            self.btnAudit.setEnabled(False)
            self.btnAdd.setEnabled(False)
            self.btnDel.setEnabled(False)

        self.xNameLineEdit.textChanged.connect(self.on_input_changed)
        self.xTableNameLineEdit.textChanged.connect(self.on_input_changed)
        self.xErrorCodeLineEdit.textChanged.connect(self.on_input_changed)
        self.xUrlLineEdit.textChanged.connect(self.on_input_changed)
        self.xMaxTimeQtyLineEdit.textChanged.connect(self.on_input_changed)

        self.xKindComboBox.currentIndexChanged.connect(self.on_input_changed)
        self.xTypeComboBox.currentIndexChanged.connect(self.on_input_changed)
        self.xLevelComboBox.currentIndexChanged.connect(self.on_input_changed)

        self.xSQLTextEdit.textChanged.connect(self.on_input_changed)
        self.xSQLTemplateTextEdit.textChanged.connect(self.on_input_changed)

        self.xMinVersionEdit.dateTimeChanged.connect(self.on_input_changed)


    def _add_form_row_two(self, layout: QGridLayout, label1_text: str, widget1: QWidget,
                        label2_text: str, widget2: QWidget, label_width: int):
        row = layout.rowCount()

        label1 = QLabel(label1_text)
        label1.setFixedWidth(label_width)
        layout.addWidget(label1, row, 0)
        layout.addWidget(widget1, row, 1)

        label2 = QLabel(label2_text)
        label2.setFixedWidth(label_width)
        layout.addWidget(label2, row, 2)
        layout.addWidget(widget2, row, 3)

    def main(self) :

        HEIGHT = 40
        layout : QVBoxLayout = QVBoxLayout()
        layout.setAlignment(Qt.AlignmentFlag.AlignTop | Qt.AlignmentFlag.AlignVCenter)
        self.setLayout(layout)
        
        

        ## 按钮: 搜索 新增
        topwidget : QWidget = QWidget()
        ##topwidget.setFixedHeight(100)
        layout.addWidget(topwidget)
        topwidget.setFixedHeight(50)
        
        # 设置背景颜色
        #topwidget.setStyleSheet("background-color: #ffff00;padding:0;margin:0;")  # 你可以将 #f0f0f0 替换为你想要的颜色代码

        toplayout : QHBoxLayout = QHBoxLayout()
        toplayout.setAlignment(Qt.AlignmentFlag.AlignRight)
        ##self.setLayout(layout)
        ##layout.addWidget(toplayout)
        topwidget.setLayout(toplayout)

        
        
        self.btnDel : QPushButton = QPushButton("删除")
        self.btnDel.setFixedHeight(HEIGHT)
        self.btnDel.setFixedWidth(150)
        self.btnDel.clicked.connect(self.btn_click_del_data)
        toplayout.addWidget(self.btnDel)

        
        
        self.btnEdit : QPushButton = QPushButton("编辑")
        self.btnEdit.setFixedHeight(HEIGHT)
        self.btnEdit.setFixedWidth(150)
        self.btnEdit.clicked.connect(self.btn_click_edit_data)
        toplayout.addWidget(self.btnEdit)


        ### 
        self.btnSave : QPushButton = QPushButton("保存")
        self.btnSave.setFixedHeight(HEIGHT)
        self.btnSave.setFixedWidth(150)
        self.btnSave.clicked.connect(self.btn_click_save_data)
        self.btnSave.setDefault(True)
        toplayout.addWidget(self.btnSave)
        

        self.btnAudit : QPushButton = QPushButton("审核")
        self.btnAudit.setFixedHeight(HEIGHT)
        self.btnAudit.setFixedWidth(150)
        self.btnAudit.clicked.connect(self.btn_click_audit_data)
        toplayout.addWidget(self.btnAudit)



        self.btnAdd : QPushButton = QPushButton("新增")
        self.btnAdd.setFixedHeight(HEIGHT)
        self.btnAdd.setFixedWidth(150)
        self.btnAdd.clicked.connect(self.button_click_add)
        self.btnAdd.setVisible(False)
        toplayout.addWidget(self.btnAdd)


        ###################

        ctrlw : QWidget = QWidget()
        ctrllayout : QHBoxLayout = QHBoxLayout()
        ctrlw.setLayout(ctrllayout)
        layout.addWidget(ctrlw)


        ctrllayout.setAlignment(Qt.AlignmentFlag.AlignRight)
        

        # 创建 ctrlw 控件（用于放置一些表单控件）
        ctrlw = QWidget()
        ctrllayout = QGridLayout()  # 使用 QGridLayout 更好控制行列
        ctrllayout.setColumnStretch(0, 1)  # 左侧 label 列
        ctrllayout.setColumnStretch(1, 3)  # 控件列
        ctrllayout.setColumnStretch(2, 1)  # 第二个 label 列
        ctrllayout.setColumnStretch(3, 3)  # 第二个控件列
        ctrlw.setLayout(ctrllayout)
        layout.addWidget(ctrlw)

        ## sID, xKind, xType, xName, xSQL, xMinVersion, xTableName, xIsStdCheck, xErrorCode, xSQLTemplate, xMaxTimeQty, xUrl, xLevel
        layout = self.layout()  # 获取已有的 QVBoxLayout 主布局

        # 创建一个 QGroupBox 容器来包含表单内容
        form_group_box = QGroupBox("检查项编辑")
        form_layout = QGridLayout()
        form_layout.setColumnStretch(0, 1)  # 标签列比例
        form_layout.setColumnStretch(1, 3)  # 控件列比例
        form_layout.setColumnStretch(2, 1)  # 标签列比例
        form_layout.setColumnStretch(3, 3)  # 控件列比例

        label_width = 120  # 所有标签统一宽度


        
        self.sIDLineEdit = QLineEdit()
        self.sIDLineEdit.setMaxLength(100)
        self.sIDLineEdit.setReadOnly(True)
        self.sIDLineEdit.setFixedHeight(HEIGHT)


        self.rProjectIDComboBox = QComboBox()
        self.rProjectIDComboBox.setFixedHeight(HEIGHT)
        self.rProjectIDComboBox.addItem("数据库检查工具", 7)
        self.rProjectIDComboBox.addItem("数据分析工具", 10)
        self.rProjectIDComboBox.addItem("定时任务", 16)
        default_index = self.rProjectIDComboBox.findText("数据库检查工具")  # 假设你想默认选中 "类型A"
        if default_index >= 0:
            self.rProjectIDComboBox.setCurrentIndex(default_index)

        
        self._add_form_row_two(form_layout, "ID:", self.sIDLineEdit,
                            "项目:", self.rProjectIDComboBox, label_width)
        

        # xKind 下拉框
        self.xKindComboBox = QComboBox()
        self.xKindComboBox.setFixedHeight(HEIGHT)
        ## self.xKindComboBox.addItems(["类型A", "类型B", "类型C"])
        # TODO 从数据库字典里读取
        kinds = listDictItem(13000006)
        if kinds is not None :
            for kind in kinds :
                self.xKindComboBox.addItem(kind["xName"], kind["xValue"])
            #self.xKindComboBox.setEditText("不限")
            default_index = self.xKindComboBox.findText("不限")  # 假设你想默认选中 "类型A"
            if default_index >= 0:
                self.xKindComboBox.setCurrentIndex(default_index)
        #self._add_form_row(form_layout, "模块:", self.xKindComboBox, label_width)

        # xType 下拉框
        self.xTypeComboBox = QComboBox()
        self.xTypeComboBox.setFixedHeight(HEIGHT)
        #self.xTypeComboBox.addItems(["选项1", "选项2", "选项3"])
        types = listDictItem(13000007)
        if types is not None :
            for type in types :
                self.xTypeComboBox.addItem(type["xName"], type["xValue"])
            #self.xKindComboBox.setEditText("不限")
            default_index = self.xTypeComboBox.findText("每天")  # 假设你想默认选中 "类型A"
            if default_index >= 0:
                self.xTypeComboBox.setCurrentIndex(default_index)

        #self._add_form_row(form_layout, "定时周期:", self.xTypeComboBox, label_width)
        
        # 模块 + 定时周期 放在同一行
        self._add_form_row_two(form_layout, "模块:", self.xKindComboBox,
                            "定时周期:", self.xTypeComboBox, label_width)

        # xName 输入框
        self.xNameLineEdit = QLineEdit()
        self.xNameLineEdit.setMaxLength(100)
        self.xNameLineEdit.setFixedHeight(HEIGHT)
        self._add_form_row(form_layout, "名称:", self.xNameLineEdit, label_width)

        # xSQL 多行文本框
        self.xSQLTextEdit = QTextEdit()
        ## TODO 设置输入最大长度
        ## 设置最少高度
        self.xSQLTextEdit.setMinimumHeight(HEIGHT * 8)
        self._add_form_row(form_layout, "检查SQL:", self.xSQLTextEdit, label_width)

        # xMinVersion 日期时间选择
        self.xMinVersionEdit = QDateTimeEdit()
        self.xMinVersionEdit.setDisplayFormat("yyyy-MM-dd")
        #self.xMinVersionEdit.setDateTime(QDateTime.currentDateTime())
        self.xMinVersionEdit.setCalendarPopup(True)  # 启用下拉日历选择
        #self.xMinVersionEdit.setReadOnly(True)
        self.xMinVersionEdit.setFocusPolicy(Qt.FocusPolicy.NoFocus)
        self.xMinVersionEdit.setFixedWidth(150)
        self.xMinVersionEdit.setFixedHeight(HEIGHT)
        #self._add_form_row(form_layout, "最低ERP版本:", self.xMinVersionEdit, label_width)

        # xIsStdCheck 勾选框
        self.xIsStdCheckCheckBox = QCheckBox("标准检查")
        self.xIsStdCheckCheckBox.setFixedHeight(HEIGHT)
        #self._add_form_row(form_layout, "标准检查:", self.xIsStdCheckCheckBox, label_width)
        
        # 最低ERP版本 + 标准检查 放在同一行
        self._add_form_row_two(form_layout, "最低ERP版本:", self.xMinVersionEdit,
                            "标准检查:", self.xIsStdCheckCheckBox, label_width)

        # xTableName 输入框
        self.xTableNameLineEdit = QLineEdit()
        self.xTableNameLineEdit.setFixedHeight(HEIGHT)
        self.xTableNameLineEdit.setMaxLength(100)
        self.xTableNameLineEdit.setPlaceholderText("如果是非标准检查,则可以设置数据表用来保存检查结果")
        #self._add_form_row(form_layout, "数据表:", self.xTableNameLineEdit, label_width)

        # xMaxTimeQty 输入框
        self.xMaxTimeQtyLineEdit = QLineEdit()
        self.xMaxTimeQtyLineEdit.setValidator(QIntValidator())  # 限制只能输入整数
        self.xMaxTimeQtyLineEdit.setFixedHeight(HEIGHT)
        #self._add_form_row(form_layout, "最长耗时限制:", self.xMaxTimeQtyLineEdit, label_width)
        # 数据表 + 最长耗时限制 放在同一行
        self._add_form_row_two(form_layout, "数据表:", self.xTableNameLineEdit,
                            "最长耗时限制:", self.xMaxTimeQtyLineEdit, label_width)

        # xErrorCode 输入框
        self.xErrorCodeLineEdit = QLineEdit()
        self.xErrorCodeLineEdit.setFixedHeight(HEIGHT)
        #self._add_form_row(form_layout, "错误代码:", self.xErrorCodeLineEdit, label_width)

        # xLevel 下拉框
        self.xLevelComboBox = QComboBox()
        self.xLevelComboBox.setFixedHeight(HEIGHT)
        #self.xLevelComboBox.addItems(["级别1", "级别2", "级别3"])
        levels = listDictItem(13000025)
        if levels is not None :
            for level in levels :
                self.xLevelComboBox.addItem(level["xName"], level["xValue"])
            default_index = self.xLevelComboBox.findText("无")  # 假设你想默认选中 "类型A"
            if default_index >= 0:
                self.xLevelComboBox.setCurrentIndex(default_index)


        #self._add_form_row(form_layout, "错误级别:", self.xLevelComboBox, label_width)
        # 错误代码 + 错误级别 放在同一行
        self._add_form_row_two(form_layout, "错误代码:", self.xErrorCodeLineEdit,
                            "错误级别:", self.xLevelComboBox, label_width)

        # xSQLTemplate 多行文本框
        self.xSQLTemplateTextEdit = QTextEdit()
        self.xSQLTemplateTextEdit.setMinimumHeight(HEIGHT * 1)
        self.xSQLTemplateTextEdit.setMaximumHeight(HEIGHT * 3)
        self._add_form_row(form_layout, "处理模板:", self.xSQLTemplateTextEdit, label_width)

        # xUrl 输入框
        self.xUrlLineEdit = QLineEdit()
        self.xUrlLineEdit.setFixedHeight(HEIGHT)
        self._add_form_row(form_layout, "文档链接:", self.xUrlLineEdit, label_width)

        form_group_box.setLayout(form_layout)
        layout.addWidget(form_group_box)

        ## 内容变更回让保存可用
        


    def _add_form_row(self, layout: QGridLayout, label_text: str, widget: QWidget, label_width: int):
        row = layout.rowCount()
        label = QLabel(label_text)
        label.setFixedWidth(label_width)
        layout.addWidget(label, row, 0)
        layout.addWidget(widget, row, 1, 1, 3)
    def load(self) :
        if self.checkid is not None and self.checkid > 0 :
            datas = query(sql=SQL_FIND, params=("", self.checkid), config=MYCONFIG)
            if datas is not None and len(datas) > 0 :
                data = datas[0]
                self.load_data(data)
        self.on_input_inited()
        
    def load_data(self, data: dict):
        """
        加载数据到编辑界面
        :param data: 字典格式的数据，如从数据库查询得到
        """
        self.handle_bind(True)
        self.data = data
        self.sIDLineEdit.setText(str(data.get("sID", "")))

        
        default_index = self.rProjectIDComboBox.findText(data.get("_Project_Name", ""))  # 假设你想默认选中 "类型A"
        if default_index >= 0:
            self.rProjectIDComboBox.setCurrentIndex(default_index)


        #self.xKindComboBox.setCurrentText(data.get("_Kind_Name", ""))
        default_index = self.xKindComboBox.findText(data.get("_Kind_Name", ""))  # 假设你想默认选中 "类型A"
        if default_index >= 0:
            self.xKindComboBox.setCurrentIndex(default_index)
        #self.xTypeComboBox.setCurrentText(data.get("_Type_Name", ""))
        #self.xTypeComboBox.setItemText(data.get("xType", 0), data.get("_Type_Name", ""))
        default_index = self.xTypeComboBox.findText(data.get("_Type_Name", ""))  # 假设你想默认选中 "类型A"
        if default_index >= 0:
            self.xTypeComboBox.setCurrentIndex(default_index)

        self.xNameLineEdit.setText(data.get("xName", ""))
        self.xSQLTextEdit.setPlainText(data.get("xSQL", ""))
        
        # xMinVersion 格式需转换为 QDateTime
        min_version = data.get("xMinVersion")
        if min_version:
            self.xMinVersionEdit.setDateTime(QDateTime.fromString(min_version, "yyyy-MM-dd HH:mm:ss"))
        
        self.xTableNameLineEdit.setText(data.get("xTableName", ""))
        self.xIsStdCheckCheckBox.setChecked(bool(data.get("xIsStdCheck", False)))
        self.xErrorCodeLineEdit.setText(str(data.get("xErrorCode", "")))
        self.xSQLTemplateTextEdit.setPlainText(data.get("xSQLTemplate", ""))
        self.xMaxTimeQtyLineEdit.setText(str(data.get("xMaxTimeQty", "")))
        self.xUrlLineEdit.setText(data.get("xUrl", ""))
        #self.xLevelComboBox.setCurrentText(data.get("_Level_Name", "")) 
        default_index = self.xLevelComboBox.findText(data.get("_Level_Name", ""))  # 假设你想默认选中 "类型A"
        if default_index >= 0:
            self.xLevelComboBox.setCurrentIndex(default_index)
        

        ## 设置是否可以修改
        # self.xKindComboBox.setEditable(self.editable)
        self.rProjectIDComboBox.setEnabled(self.editable)
        self.xKindComboBox.setEnabled(self.editable)
        self.xTypeComboBox.setEnabled(self.editable)
        self.xNameLineEdit.setReadOnly(not self.editable)
        ##self.xSQLTextEdit.setDisabled (not self.editable)
        self.xSQLTextEdit.setReadOnly(not self.editable)
        self.xMinVersionEdit.setReadOnly(not self.editable)
        self.xTableNameLineEdit.setReadOnly(not self.editable)
        
        self.xIsStdCheckCheckBox.setCheckable(self.editable)
        self.xErrorCodeLineEdit.setReadOnly(not self.editable)
        self.xSQLTemplateTextEdit.setReadOnly(not self.editable)
        self.xMaxTimeQtyLineEdit.setReadOnly(not self.editable)
        self.xUrlLineEdit.setReadOnly(not self.editable)
        self.xLevelComboBox.setEnabled(self.editable)
        
        ## 判断按钮
        #self.btnSave.enable( , logdir=None, context=5, format="html")
        # self.btnSave.setEnabled(False)
        # self.btnEdit.setEnabled(True)
        # self.btnAudit.setEnabled(True)
        # self.btnAdd.setEnabled(True)
        self.on_input_inited()
        self.handle_bind(False)

        s : int = int(data.get("sStatus"))
        if s > 2 :
            self.btnAudit.setText("已审核")
            self.btnAudit.setEnabled(False)
            self.btnAudit.setDisabled(True)
        else :
            self.btnAudit.setText("待审核")
            self.btnAudit.setEnabled(True)

        if self.checkid is not None and self.checkid > 0 :
            self.rProjectIDComboBox.setEnabled(False)

    
    
    def btn_click_del_data(self) :
        ## 先检查下能不能删
        self.editable = True
        params = (self.checkid)
        #exec("delete from yt_check WHERE sID = %d", params)
        vs = proc("yp_check_del", {"pID": self.checkid}, outputparam=True )
        print(vs)
        QMessageBox.information(self, "保存成功", "删除成功！")
        self.close()

    def btn_click_edit_data(self) :
        self.editable = True
        params = (self.checkid)
        exec(sql="UPDATE yt_check SET sStatus = 2, sVersion = ISNULL(sVersion, 0) + 1, sLastUpdate = GETDATE() WHERE sID = %d", params=params,config=MYCONFIG)
        self.on_input_inited()
        self.load()
        self.btnEdit.setDisabled(True)
        self.btnDel.setEnabled(True)

    def btn_click_audit_data(self) :
        self.editable = False
        params = (self.checkid)
        exec("UPDATE yt_check SET sStatus = 5, sVersion = ISNULL(sVersion, 0) + 1, sLastUpdate = GETDATE() WHERE sID = %d", params,MYCONFIG)
        QMessageBox.information(self, "保存成功", "数据保存成功！")
        self.on_input_inited()
        self.load()

        # 继续保存逻辑...
    def btn_click_save_data(self) -> dict:
        """
        从界面控件提取数据，返回字典格式
        """
        # print("开始打印 xTypeComboBox 的内容：")
        # for i in range(self.xTypeComboBox.count()):
        #     text = self.xTypeComboBox.itemText(i)
        #     data = self.xTypeComboBox.itemData(i)
        #     print(f"Item {i}: Text='{text}', UserData={data}")
        # 判断是否已有sID,有的话就是修改,否则就是新增
        
        if not self.xNameLineEdit.text().strip():
            QMessageBox.warning(self, "提示", "名称不能为空！")
            return
        if not self.xSQLTextEdit.toPlainText().strip():
            QMessageBox.warning(self, "提示", "检查SQL不能为空！")
            return


        _data_ = {
            "xKind": self.xKindComboBox.currentData(),
            "xType": self.xTypeComboBox.currentData(),
            "xName": self.xNameLineEdit.text().strip(),
            "xSQL": self.xSQLTextEdit.toPlainText().strip(),
            "xMinVersion": self.xMinVersionEdit.dateTime().toString("yyyy-MM-dd HH:mm:ss"),
            "xTableName": self.xTableNameLineEdit.text().strip(),
            "xIsStdCheck": int(self.xIsStdCheckCheckBox.isChecked()),  # 转为整数 0/1
            "xErrorCode": self.xErrorCodeLineEdit.text().strip(),
            "xSQLTemplate": self.xSQLTemplateTextEdit.toPlainText().strip(),
            "xMaxTimeQty": self.xMaxTimeQtyLineEdit.text().strip(),
            "xUrl": self.xUrlLineEdit.text().strip(),
            # "xLevel": self.xLevelComboBox.currentText()
            "xLevel": self.xLevelComboBox.currentData(),
            "rProject_ID": self.rProjectIDComboBox.currentData()
        }
        ## 项目 不可改
        if self.checkid is not None and self.checkid > 0 :
            sql = """UPDATE dbo.yt_check 
    SET xKind = %d,xType = %d,xName = %s,xSQL = %s,xMinVersion = %s,xTableName = %s,xIsStdCheck = %d,xErrorCode = %d,xSQLTemplate = %s,xMaxTimeQty = %d,xUrl = %s,xLevel = %d
    , sVersion = isnull(sVersion, 0) + 1, sLastUpdate = getdate()
    WHERE sID= %d
    """
            params = (_data_["xKind"], _data_["xType"], _data_["xName"], _data_["xSQL"], _data_["xMinVersion"], _data_["xTableName"], _data_["xIsStdCheck"], _data_["xErrorCode"], _data_["xSQLTemplate"], _data_["xMaxTimeQty"], _data_["xUrl"], _data_["xLevel"], self.checkid)
            exec(sql, tuple(params),MYCONFIG)
        else :
            pass
            # 生成一个ID, 而且等下是INSERT
            self.checkid = yp_getid("yt_check", "sID")
            sql = """INSERT INTO dbo.yt_check (
	sID, xKind, xType, xName, xSQL, xMinVersion, sStatus, sVersion, sCreateTime, sLastUpdate, xTableName, xIsStdCheck, xIsProc, xErrorCode, xSQLTemplate, xMaxTimeQty, xUrl, xLevel,rProject_ID
)
VALUES (
	%d		-- sID - int
	, %d	-- xKind - int
	, %d	-- xType - int
	, %s	-- xName - nvarchar(128)
	, %s	-- xSQL - nvarchar(max)
	, %s	-- xMinVersion - datetime2(0)
	, 2	-- sStatus - int
	, 1	-- sVersion - int
	, GETDATE()	-- sCreateTime - datetime2(0)
	, GETDATE()	-- sLastUpdate - datetime2(0)
	, %s	-- xTableName - nvarchar(255)
	, %d	-- xIsStdCheck - smallint
	, 0	-- xIsProc - smallint
	, %d	-- xErrorCode - int
	, %s	-- xSQLTemplate - nvarchar(max)
	, %d	-- xMaxTimeQty - int
	, %s	-- xUrl - nvarchar(1024)
	, %d	-- xLevel - int
    , %d
)"""
            params = (self.checkid, _data_["xKind"], _data_["xType"], _data_["xName"], _data_["xSQL"], _data_["xMinVersion"], _data_["xTableName"], _data_["xIsStdCheck"], _data_["xErrorCode"], _data_["xSQLTemplate"], _data_["xMaxTimeQty"], _data_["xUrl"], _data_["xLevel"], _data_["rProject_ID"])
            exec(sql, tuple(params),MYCONFIG)
        ## 提示保存OK
        
        self.editable = False
        QMessageBox.information(self, "保存成功", "数据保存成功！")
        #self.on_input_inited()
        self.load()
        #self.close()

    






# if __name__ == "__main__" :     ## or 1 == 1
#     app = QApplication([])
#     w = WWarningEditor()
#     ## w = WScriptWindow()
#     w.show()
#     app.exec()